import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {InterceptedResponse} from './intercepted-response';
import {Injectable} from '@angular/core';
// import {HttpHeaders} from '@angular/common/http';
// import {Observable,of} from 'rxjs';

@Injectable()
export class InterceptorService {
  constructor(private http: HttpClient) {
  }

  get(url: string, options?: any): Observable<InterceptedResponse> {
    return Observable.create((observer) => {
      this.http.get(url, options).toPromise().then(response => {
        observer.next(response as any)
        observer.complete();
      }).catch(err => {
        observer.error(err);
        return
      });
    });
  }

  post(url: string, body: any | null, options?: any): Observable<InterceptedResponse> {
    return Observable.create((observer) => {
      this.http.post(url, body, options).toPromise().then(response => {
        observer.next(response as any)
        observer.complete();
      }).catch(err => {
        observer.error(err);
        return
      });
    });
  }

  delete(url: string, options?: any): Observable<InterceptedResponse> {
    return Observable.create((observer) => {
      this.http.delete(url, options).toPromise().then(response => {
        observer.next(response as any)
        observer.complete();
      }).catch(err => {
        observer.error(err);
        return
      });
    });
  }

  put(url: string, options?: any): Observable<InterceptedResponse> {
    return Observable.create((observer) => {
      this.http.put(url, options).toPromise().then(response => {
        observer.next(response as InterceptedResponse)
        observer.complete();
      }).catch(err => {
        observer.error(err);
      });
    });
  }
}

